#include "CServer.h"
#include "ConfigMgr.h"
#include "boost/asio.hpp"
#include <iostream>
#include "RedisMgr.h"
#include "const.h"
#include "ChatServiceImpl.h"
#include <grpcpp/grpcpp.h>
#include <memory>
#include <thread>



int main()
{
    auto& cfg = ConfigMgr::GetInstance();
    short port = std::stoi(cfg["SelfServer"]["Port"]);
    std::string server_name = cfg["SelfServer"]["Name"];

    try
    {
        boost::asio::io_context ioc;
        CServer server(ioc,port);

        // 将登陆数设置为0
        RedisMgr::GetInstance()->HSet(LOGIN_COUNT,server_name,"0");
        // 新开一个线程启动gRPC服务
        std::string grpc_address = cfg["SelfServer"]["Host"]+":"+cfg["SelfServer"]["RPCPort"];
        ChatServiceImpl service;

        ::grpc::ServerBuilder builder;
        builder.AddListeningPort(grpc_address,::grpc::InsecureServerCredentials());

        builder.RegisterService(&service);
        std::unique_ptr<::grpc::Server> grpcServer(builder.BuildAndStart());
        
        std::thread grpc_thread([&grpcServer](){
            std::cout<<"chatserver2 grpc server started "<<std::endl;
            grpcServer->Wait();
        });


        boost::asio::signal_set signals(ioc,SIGINT,SIGTERM);
        signals.async_wait([&ioc,&grpcServer](const boost::system::error_code& ec, int signo){
            std::cerr<<"signal "<<signo<<" received,exit..."<<std::endl;
            ioc.stop();
            grpcServer->Shutdown();
        });
        ioc.run();
        grpc_thread.join();
        //等服务器对应的登陆的键值从redis中删除
        RedisMgr::GetInstance()->HDel(LOGIN_COUNT,server_name);
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << '\n';
    }
    
    

    return 0;
}